// Copyright 2022 jeff.li. and/or its affiliates.

#include <tbir/runtime/type_name_traits.h>

#include <mutex>

namespace tbir::runtime {

    struct TypeNameTraits::Manager {
        // mutex
        static std::mutex s_mutex_;
        static TypeNameTraits *s_instance_;

        Manager() = default;

        static TypeNameTraits *Global() {
            if (s_instance_ == nullptr) {
                std::lock_guard<std::mutex> lock(s_mutex_);
                if (s_instance_ == nullptr) {
                    s_instance_ = new TypeNameTraits();
                }
            }
            return s_instance_;
        }
    };

    std::mutex TypeNameTraits::Manager::s_mutex_{};
    TypeNameTraits *TypeNameTraits::Manager::s_instance_{nullptr};

    TypeNameTraits &TypeNameTraits::Register(std::type_index ty_idx, string_view name) {
        Manager::Global()->type_info_[ty_idx] = name;
        return *Manager::Global();
    }

    string_view TypeNameTraits::Get(std::type_index ty_idx) {
        auto ptr = Manager::Global();
        auto itr = ptr->type_info_.find(ty_idx);
        return itr == ptr->type_info_.end() ? "" : itr->second;
    }

}  // namespace tbir::runtime
